# -*- coding:utf-8 -*-

"""
商品标题黑名单Service
"""

from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime

from module_admin.dao.title_blacklist_dao import TitleBlacklistDao
from module_admin.entity.do.title_blacklist_do import TitleBlacklist
from utils.log_util import logger


class TitleBlacklistService:
    """商品标题黑名单业务逻辑层"""
    
    @classmethod
    async def get_list(cls, db: AsyncSession, query_dict: dict = None, user_id: int = None):
        """
        获取标题黑名单列表（按用户隔离）
        
        Args:
            db: 数据库会话
            query_dict: 查询条件字典
            user_id: 用户ID，如果提供则只获取该用户的黑名单
        """
        return await TitleBlacklistDao.get_list(db, query_dict, user_id=user_id)
    
    @classmethod
    async def get_by_id(cls, db: AsyncSession, blacklist_id: int):
        """
        根据ID获取标题黑名单
        """
        return await TitleBlacklistDao.get_by_id(db, blacklist_id)
    
    @classmethod
    async def add(cls, db: AsyncSession, blacklist_data: dict):
        """
        新增标题黑名单
        
        Args:
            blacklist_data: {
                'keyword': '关键字',
                'match_type': 'contains/equals/regex',
                'reason': '拉黑原因',
                'remark': '备注'
            }
        """
        # 检查关键字是否已存在
        keyword = blacklist_data.get('keyword')
        if not keyword:
            raise ValueError("关键字不能为空")
        
        # ✅ 获取用户ID（从blacklist_data或create_by字段）
        user_id = blacklist_data.get('create_by')
        if user_id:
            try:
                user_id = int(user_id)
            except (ValueError, TypeError):
                user_id = None
        
        exists = await TitleBlacklistDao.check_exists(db, keyword, user_id=user_id)
        if exists:
            raise ValueError(f"关键字 '{keyword}' 已在黑名单中")
        
        # ✅ 修复：create_by和dept_id应该是Integer类型，不能是空字符串
        create_by = blacklist_data.get('create_by')
        dept_id = blacklist_data.get('dept_id')
        
        # 如果create_by为空或不是整数，使用默认值1（或抛出错误）
        if create_by is None or create_by == '':
            create_by = 1  # 默认管理员ID
        else:
            create_by = int(create_by)
        
        # 如果dept_id为空，使用默认值
        if dept_id is None or dept_id == '':
            dept_id = 1  # 默认部门ID
        else:
            dept_id = int(dept_id)
        
        blacklist = TitleBlacklist(
            keyword=keyword,
            match_type=blacklist_data.get('match_type', 'contains'),
            reason=blacklist_data.get('reason'),  # reason可以为空（可选字段）
            remark=blacklist_data.get('remark'),
            status=blacklist_data.get('status', '0') or '0',  # ✅ 添加status字段，默认'0'（启用）
            create_by=create_by,
            dept_id=dept_id,
            create_time=datetime.now(),
            del_flag='0'
        )
        
        await TitleBlacklistDao.add(db, blacklist)
        await db.commit()
        
        logger.info(f"添加标题黑名单: {keyword} ({blacklist_data.get('match_type', 'contains')})")
        return blacklist
    
    @classmethod
    async def update(cls, db: AsyncSession, blacklist_id: int, update_data: dict):
        """
        更新标题黑名单
        """
        update_data['update_time'] = datetime.now()
        await TitleBlacklistDao.update(db, blacklist_id, update_data)
        await db.commit()
        
        logger.info(f"更新标题黑名单: ID={blacklist_id}")
    
    @classmethod
    async def delete(cls, db: AsyncSession, blacklist_id: int):
        """
        删除标题黑名单
        """
        await TitleBlacklistDao.delete(db, blacklist_id)
        await db.commit()
        
        logger.info(f"删除标题黑名单: ID={blacklist_id}")
    
    @classmethod
    async def batch_delete(cls, db: AsyncSession, blacklist_ids: list):
        """
        批量删除标题黑名单
        """
        for blacklist_id in blacklist_ids:
            await TitleBlacklistDao.delete(db, blacklist_id)
        
        await db.commit()
        logger.info(f"批量删除标题黑名单: {len(blacklist_ids)}条")

